package com.rong.DAO;
// default package

import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import com.opensymphony.xwork2.ActionContext;
import com.rong.hibernate.*;
import com.rong.ORM.ZynCar;
import com.rong.ORM.ZynCompany;
import com.rong.ORM.ZynUser;

/**
 * A data access object (DAO) providing persistence and search support for
 * ZynCar entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see .ZynCar
 * @author MyEclipse Persistence Tools
 */

public class ZynCarDAO extends BaseHibernateDAO {
	private static final Log log = LogFactory.getLog(ZynCarDAO.class);
	// property constants
	public static final String NUM = "num";
	public static final String COMPANY = "company";
	public static final String DRIVER = "driver";
	public static final String ENGINE_NUM = "engineNum";
	public static final String ENGINE_POWER = "enginePower";
	public static final String ENGINE_VOLUME = "engineVolume";
	public static final String EXT_ATTR1 = "extAttr1";
	public static final String EXT_ATTR2 = "extAttr2";
	public static final String EXT_ATTR3 = "extAttr3";
	public static final String EXT_ATTR4 = "extAttr4";
	public static final String EXT_ATTR5 = "extAttr5";

	public void save(ZynCar transientInstance) {
		log.debug("saving ZynCar instance");
		try {
			
			//getSession().save(transientInstance);
			
			 Transaction ts = null;
             ts = getSession().beginTransaction();
		     getSession().save(transientInstance);
		     ts.commit();
		            
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}
	public void update(ZynCar transientInstance) {
		log.debug("updating ZynCar instance");
		try {
			
			 Transaction ts = null;
             ts = getSession().beginTransaction();
		     getSession().update(transientInstance);
		     ts.commit();
		     
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}
	public void delete(ZynCar persistentInstance) {
		log.debug("deleting ZynCar instance");
		try {
			//getSession().delete(persistentInstance);
			
			 Transaction ts = null;
             ts = getSession().beginTransaction();
		     getSession().delete(persistentInstance);
		     ts.commit();
		     
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public ZynCar findById(java.lang.Integer id) {
		log.debug("getting ZynCar instance with id: " + id);
		try {
			//ZynCar instance = (ZynCar) getSession().get("ZynCar", id);
			ZynCar instance = (ZynCar) getSession().load(ZynCar.class, id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(ZynCar instance) {
		log.debug("finding ZynCar instance by example");
		try {
			List results = getSession().createCriteria("ZynCar").add(
					Example.create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding ZynCar instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from ZynCar as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByNum(Object num) {
		return findByProperty(NUM, num);
	}

	public List findByCompany(Object company) {
		return findByProperty(COMPANY, company);
	}

	public List findByDriver(Object driver) {
		return findByProperty(DRIVER, driver);
	}

	public List findByEngineNum(Object engineNum) {
		return findByProperty(ENGINE_NUM, engineNum);
	}

	public List findByEnginePower(Object enginePower) {
		return findByProperty(ENGINE_POWER, enginePower);
	}

	public List findByEngineVolume(Object engineVolume) {
		return findByProperty(ENGINE_VOLUME, engineVolume);
	}

	public List findByExtAttr1(Object extAttr1) {
		return findByProperty(EXT_ATTR1, extAttr1);
	}

	public List findByExtAttr2(Object extAttr2) {
		return findByProperty(EXT_ATTR2, extAttr2);
	}

	public List findByExtAttr3(Object extAttr3) {
		return findByProperty(EXT_ATTR3, extAttr3);
	}

	public List findByExtAttr4(Object extAttr4) {
		return findByProperty(EXT_ATTR4, extAttr4);
	}

	public List findByExtAttr5(Object extAttr5) {
		return findByProperty(EXT_ATTR5, extAttr5);
	}

	public List findAll() {
		log.debug("finding all ZynCar instances");
		try {
			String queryString = "from ZynCar";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public ZynCar merge(ZynCar detachedInstance) {
		log.debug("merging ZynCar instance");
		try {
			//ZynCar result = (ZynCar) getSession().merge(detachedInstance);
			 Transaction ts = null;
             ts = getSession().beginTransaction();
             ZynCar result=(ZynCar)getSession().merge(detachedInstance);
		     ts.commit();
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	
	/**
	 * 查找并返回符合条件的公司this.getQuery_carnum(),this.getQuery_driver(),this.getQuery_blongto(),this.getQuery_cub(),this.getQuery_oil(),this.getQuery_big()
	 */

	public List<ZynCar> findCarQueryByPage(int page, int rowsPerPage,String carnum,String driver,int blongto,double cub,double oil,String big) {
		
		ActionContext actionContext = ActionContext.getContext();         
	     Map session = actionContext.getSession(); 
	     ZynUser loginUser=(ZynUser)session.get("loginUser");   //登录用户	
	
		Transaction ts2=null;
		ts2=getSession().beginTransaction();
		getSession().clear();
				
		Criteria crt = getSession().createCriteria(ZynCar.class);
		crt.addOrder(org.hibernate.criterion.Order.desc("id"));
		
		if(carnum!=null&&!carnum.equalsIgnoreCase("")){			//车牌
			crt.add(Restrictions.like("num", carnum,MatchMode.ANYWHERE));
		}
	
		if(driver!=null&&!driver.equalsIgnoreCase("")){			//司机
			crt.add(Restrictions.like("driver", driver,MatchMode.ANYWHERE));
		}
		if(big!=null&&!big.equalsIgnoreCase("")){			//型号，大，中，小
			crt.add(Restrictions.eq("extAttr4", big));
		}
		
		if(cub>0){			//水箱容积
			crt.add(Restrictions.ge("extAttr3", String.valueOf(cub)));
		}
		if(oil>0){			//油耗
			crt.add(Restrictions.ge("extAttr2", String.valueOf(oil)));
		}
		
	
		//--权限判断,分公司只能看本公司单据，本部可以查看全部		
		if(loginUser.getZyncom().getComProperty().equalsIgnoreCase(Const.comTypetop)){			
			//总部
			if(blongto>-1){			//所属分公司
				crt.add(Restrictions.eq("company",String.valueOf(blongto)));
			}
		}else{			
					//所属分公司
				crt.add(Restrictions.eq("company", String.valueOf(loginUser.getComId())));
			  //匹配单据的所属公司
		}
		
		
		crt.setMaxResults(rowsPerPage); // 每页最多显示几条
		crt.setFirstResult((page - 1) * rowsPerPage); // 每页从第几条记录开始
		ts2.commit();
		List<ZynCar> list = crt.list();
		for (int i = 0; i < list.size(); i++) {
			System.out.println("==========comlist by query======"+list.get(i).getNum());
			
		}
        
		

		return list;
	}
	/**
	 * 查找并返回所有公司数
	 */

	public List<ZynCar> carTatolRows(String carnum,String driver,int blongto,double cub,double oil,String big) {
		getSession().clear();

		ActionContext actionContext = ActionContext.getContext();         
	     Map session = actionContext.getSession(); 
	     ZynUser loginUser=(ZynUser)session.get("loginUser");   //登录用户	
	     Criteria crt = getSession().createCriteria(ZynCar.class);
			crt.addOrder(org.hibernate.criterion.Order.desc("id"));
			
			if(carnum!=null&&!carnum.equalsIgnoreCase("")){			//车牌
				crt.add(Restrictions.like("num", carnum,MatchMode.ANYWHERE));
			}
		
			if(driver!=null&&!driver.equalsIgnoreCase("")){			//司机
				crt.add(Restrictions.like("driver", driver,MatchMode.ANYWHERE));
			}
			if(big!=null&&!big.equalsIgnoreCase("")){			//型号，大，中，小
				crt.add(Restrictions.eq("extAttr4", big));
			}
			
			if(cub>0){			//水箱容积
				crt.add(Restrictions.ge("extAttr3", String.valueOf(cub)));
			}
			if(oil>0){			//油耗
				crt.add(Restrictions.ge("extAttr2", String.valueOf(oil)));
			}
			
		
			//--权限判断,分公司只能看本公司单据，本部可以查看全部		
			if(loginUser.getZyncom().getComProperty().equalsIgnoreCase(Const.comTypetop)){			
				//总部
				if(blongto>-1){			//所属分公司
					crt.add(Restrictions.eq("company",String.valueOf(blongto)));
				}
			}else{			
						//所属分公司
					crt.add(Restrictions.eq("company", String.valueOf(loginUser.getComId())));
				  //匹配单据的所属公司
			}
			
			
		List<ZynCar> list = crt.list();
		return list;
	}

	public void attachDirty(ZynCar instance) {
		log.debug("attaching dirty ZynCar instance");
		try {
			getSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(ZynCar instance) {
		log.debug("attaching clean ZynCar instance");
		try {
			getSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
}